package com.share.admin.config.security.bean;

import com.alibaba.fastjson.JSON;
import com.share.common.common.Result;
import com.share.common.enums.ErrMsgEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@Component("accessDeniedHandler")
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");

        log.error("访问异常-该用户权限不足", e);
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(Result.failure(ErrMsgEnum.UN_PERMISSION)));
        writer.flush();
        writer.close();
    }
}
